import React, { useEffect } from 'react';
import { usePoints } from '../PointsContext';
import { useAuth } from '../../auth/AuthContext';

const PointsHistory: React.FC = () => {
  const { transactions, loading, getTransactionHistory } = usePoints();
  const { user } = useAuth();

  useEffect(() => {
    if (user) {
      getTransactionHistory();
    }
  }, [user]);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN');
  };

  const getTransactionTypeText = (type: string) => {
    switch (type) {
      case 'upload': return '上传资源';
      case 'download': return '下载资源';
      case 'share': return '分享奖励';
      case 'bonus': return '系统奖励';
      default: return '其他';
    }
  };

  if (loading) {
    return <div className="text-center py-4">加载中...</div>;
  }

  return (
    <div className="max-w-4xl mx-auto mt-8 p-6 bg-white rounded-lg shadow-md">
      <h2 className="text-2xl font-bold mb-6">积分历史</h2>
      {transactions.length === 0 ? (
        <p className="text-center text-gray-500">暂无积分记录</p>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50">
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  时间
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  类型
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  积分变动
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  描述
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {transactions.map((transaction) => (
                <tr key={transaction.id}>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {formatDate(transaction.createdAt)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {getTransactionTypeText(transaction.type)}
                  </td>
                  <td className={`px-6 py-4 whitespace-nowrap text-sm ${transaction.points > 0 ? 'text-green-600' : 'text-red-600'}`}>
                    {transaction.points > 0 ? `+${transaction.points}` : transaction.points}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500">
                    {transaction.description}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

export default PointsHistory;